package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.BaseException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * TODO
 *
 * @Author mr.wu
 * @Data #{DATE} #{TIME}
 */
@Service
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private WebSocketServer webSocketServer;
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    @Override
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + outTradeNo);

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 历史订单查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Long userId = BaseContext.getCurrentId();
        dto.setUserId(userId);
        List<OrderVO> vo = ordersMapper.historyOrders(dto);
        vo.forEach(x -> {
            List<OrderDetail> list = orderDetailMapper.historyOrderDetail(x.getId());
            x.setOrderDetailList(list);
        });
        Page<OrderVO> page = (Page) vo;
        PageResult result = new PageResult();
        result.setTotal(page.getTotal());
        result.setRecords(page.getResult());
        return result;
    }

    /**
     * 查询订单详情（订单id）
     *
     * @param orderId
     * @return
     */
    @Override
    public OrderVO orderDetail(Integer orderId) {
        Orders orders = ordersMapper.getorderDetail(orderId);
        OrderVO vo = new OrderVO();
        BeanUtils.copyProperties(orders, vo);
        List<OrderDetail> list = orderDetailMapper.historyOrderDetail(Long.valueOf(orderId));
        vo.setOrderDetailList(list);
        return vo;
    }

    /**
     * 取消订单
     *
     * @param id
     * @return
     */
    @Override
    public void cancel(Integer id) {
        Orders orders = new Orders();
        orders.setId(Long.valueOf(id));
        orders.setStatus(Orders.CANCELLED);
        ordersMapper.update(orders);
    }

    /**
     * 再来一单
     *
     * @param id
     * @return
     */
    @Override
    public void repetition(Integer id) {
        Orders orders = ordersMapper.getorderDetail(id);
        orders.setOrderTime(LocalDateTime.now());
        ordersMapper.insert(orders);
        List<OrderDetail> list = orderDetailMapper.historyOrderDetail(Long.valueOf(id));
        orderDetailMapper.insertBatch(list);
    }

    /**
     * 完成订单
     *
     * @param id
     * @return
     */
    @Override
    public void complete(Integer id) {
        Orders orders = new Orders();
        orders.setId(Long.valueOf(id));
        orders.setStatus(Orders.COMPLETED);
        ordersMapper.update(orders);
    }

    /**
     * 订单搜索
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<OrderVO> vo = ordersMapper.conditionSearch(dto);

        vo.forEach(x -> {
            List<OrderDetail> list = orderDetailMapper.historyOrderDetail(x.getId());
            list.forEach(detail -> {
                Dish dish = dishMapper.getPcDish(detail.getDishId());
                x.setOrderDishes(dish.getName());
            });
        });

        Page<OrderVO> page = (Page) vo;
        PageResult result = new PageResult();
        result.setTotal(page.getTotal());
        result.setRecords(page.getResult());
        return result;
    }

    /**
     * 取消订单
     *
     * @param dto
     * @return
     */
    @Override
    public void adminCancel(OrdersCancelDTO dto) {
        Orders orders = new Orders();
        orders.setStatus(Orders.CANCELLED);
        orders.setId(dto.getId());
        orders.setCancelReason(dto.getCancelReason());
        ordersMapper.update(orders);
    }
    /**
     * 各个状态的订单数量统计
     *
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO vo = new OrderStatisticsVO();
        List<Map<String, Object>> map = ordersMapper.statistics();
        return vo;
    }
    /**
     * 拒单
     *
     * @param dto
     * @return
     */
    @Override
    public void rejection(OrdersRejectionDTO dto) {
        Orders orders = new Orders();
        orders.setStatus(Orders.CANCELLED);
        orders.setId(dto.getId());
        orders.setRejectionReason(dto.getRejectionReason());
        ordersMapper.update(orders);
    }
    /**
     * 接单
     *
     * @param id
     * @return
     */
    @Override
    public void confirm(Integer id) {
        Orders orders = new Orders();
        orders.setStatus(Orders.CONFIRMED);
        orders.setId(Long.valueOf(id));
        ordersMapper.update(orders);
    }

    /**
     * 派送订单
     *
     * @param id
     * @return
     */
    @Override
    public void delivery(Integer id) {
        Orders orders = new Orders();
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orders.setId(Long.valueOf(id));
        ordersMapper.update(orders);
    }

    /**
     * 催单
     *
     * @param id
     * @return
     */
    @Override
    public void reminder(Integer id) {
        Orders orders = ordersMapper.getorderDetail(id);
        if(orders==null){
            throw new BaseException("该订单不存在");
        }
        Map map = new HashMap<>();
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 提交订单
     *
     * @return
     */
    @Transactional
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO dto) {
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());

        ShoppingCart shoppingCart = new ShoppingCart();
        Long userId = BaseContext.getCurrentId();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> cart = cartMapper.getCart(shoppingCart);
        if (CollectionUtils.isEmpty(cart) && cart.size() == 0) {
            throw new BaseException("购物车为空");
        }

        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);
        String number = UUID.randomUUID().toString().replace("-", "");
        orders.setNumber(number);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setUserId(userId);
        orders.setConsignee(addressBook.getConsignee());
        ordersMapper.insert(orders);

        //订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart c : cart) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(c, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);

        cartMapper.delete(userId);

        OrderSubmitVO vo = new OrderSubmitVO();
        vo.setId(orders.getId());
        vo.setOrderAmount(orders.getAmount());
        vo.setOrderNumber(orders.getNumber());
        vo.setOrderNumber(String.valueOf(orders.getOrderTime()));
        return vo;
    }
}
